<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Common\Model\ColumnLiveAdminModel;

class AdminUserController extends AdminbaseController{
	protected $user_admin_model;
	protected $self_admin_model;
	protected $area_model;
	protected $company_model;
	protected $sys_menu_model;
	protected $sys_menu_admin_model;
	protected $manage_personnel_sys_menu_id;

	function _initialize() {
		parent::_initialize();
		$this->user_admin_model = D("Common/AdminUser");
		$this->area_model = D("Common/Area");
		$this->company_model = M('vrnews1.company');
		$this->sys_menu_model = M('vradmin1.sys_menu');
		$admin_id = $_SESSION['ADMIN_ID'];
		$this->self_admin_model = $this->user_admin_model->where('admin_id = '.$admin_id)->find();
		$this->sys_menu_admin_model = M('vradmin1.sys_menu_admin');

		$manage_personnel = $this->sys_menu_model->field('menu_id')->where(array('name'=>'员工管理', 'parentid'=>0))->find();
		$this->manage_personnel_sys_menu_id = $manage_personnel['menu_id'];
	}


	function index(){
		if($this->self_admin_model['type'] == '2'){
			$this->assign("data", $this->self_admin_model);
			$this->assign("type", $this->self_admin_model['type']);
			$this->display();
		}else{
			$formParam['adminUserName'] = I('param.adminUserName', '');
			$this->assign("formParam", $formParam);

			$currentPage = I('param.p', 0);
			if ($currentPage <= 0) {
				$currentPage = 1;
			}

			$pageSize = '20';
			$pageStart = ($currentPage - 1) * $pageSize;
			$pageEnd = $currentPage * $pageSize;
			$result = $this->user_admin_model->getUserAdminList($formParam['adminUserName'],$pageStart,$pageSize);

			//分页
			$page = $this->page($result['count_Total'], 20);
			$this->assign("page", $page->show('Admin'));


			foreach($result['data'] as $key=>$value){
				//权限
				$result['data'][$key]['role_list'] = $this->user_admin_model->getColumnRole($value['admin_id']);
			}

//			$count_data[] = 20 - $count_total;
//
//			$this->assign("count_data", $count_data);
			$this->assign("data", $result['data']);
			$this->assign("type", $this->self_admin_model['type']);
			$this->display();
		}
	}

	/**
	 * 进入添加业务管理员页面
	 */
	function adminUserAdd()
	{
		$this->assign("Title", "业务管理员");

		//所有的权限
		$role_list = $this->user_admin_model->getColumnRole('', $this->manage_personnel_sys_menu_id);

		//所有已开通的地区地区列表
		$established_area_list = $this->area_model->getChooseAreaList(1);

		//三  所有的公司
		$all_company = $this->company_model->where(array('status'=>1))->select();

		//四 所属角色
		$admin_id = $_SESSION['ADMIN_ID'];
		$role = M("vradmin1.role", null);
		if($admin_id == '1'){
			$role_info = $role->select();
		}else{
			$role_info = $role->where("is_son_show = 1")->select();
		}

		$this->assign('all_company', $all_company);
		$this->assign("role_data", $role_list);
		$this->assign("established_area_data", $established_area_list);
		$this->assign("role_info", $role_info);
		$this->display('adminuseradd');
	}


	/**
	 * 进入修改权限页面
	 */
	function editRole()
	{
		$admin_id = I("param.admin_id", "");

		if (empty($admin_id)) {
			$this->error("参数错误！");
		}

		$admin_user_column_role_arr = array();
		$admin_user_sys_menu_role_arr = array();
		$area_role_id_arr = array();
		$area_role_name_arr = array();

		//获取用户已有权限
		$admin_user_role_list = $this->user_admin_model->getColumnRole($admin_id, $this->manage_personnel_sys_menu_id);

		foreach($admin_user_role_list['column_role'] as $column_role_value){
			$admin_user_column_role_arr[] = $column_role_value['column_id'];
		}
		foreach($admin_user_role_list['sys_menu_role'] as $sys_menu_role_value){
			$admin_user_sys_menu_role_arr[] = $sys_menu_role_value['menu_id'];
		}
		foreach($admin_user_role_list['area_role'] as $area_role_value){
			$area_role_id_arr[] = $area_role_value['area_id'];
			$area_role_name_arr[] = $area_role_value['name'];
		}

		//如果有员工管理权限  取出公司ID
		if($admin_user_sys_menu_role_arr){
			foreach ($admin_user_sys_menu_role_arr as $key=>$val) {
				if($val == $this->manage_personnel_sys_menu_id){
					$company_info = $this->sys_menu_admin_model->alias('s')->field('c.*')->join('RIGHT JOIN vrnews1.company c ON c.company_id=s.company_id')->where(array('s.menu_id'=>$val, 's.admin_id'=>$admin_id))->find();
				}
			}
		}
		$company_info = $this->user_admin_model->alias('a')->join('left JOIN vrnews1.company c ON c.company_id=a.company_id')->where(['a.admin_id'=>$admin_id])->find();
		//所有的权限
		$role_list = $this->user_admin_model->getColumnRole('', $this->manage_personnel_sys_menu_id);
//return print_r($role_list);
		//所有已开通的地区地区列表
		$established_area_list = $this->area_model->getChooseAreaList(1);

		//三  所有的公司
		$all_company = $this->company_model->where(array('status'=>1))->select();

		//四 所属角色
		$login_admin_id = $_SESSION['ADMIN_ID'];
		$role = M("vradmin1.role", null);
		if($login_admin_id == '1'){
			$role_info = $role->select();
		}else{
			$role_info = $role->where("is_son_show = 1")->select();
		}
		if($role_info && count($role_info) > 0){
			foreach ($role_info as $key=>$value){
				$admin_role = M("vradmin1.admin_role", null);
				$admin_role_info = $admin_role->where("admin_id = '".$admin_id."' and role_id = '".$value['role_id']."'")->find();
				if($admin_role_info){
					$role_info[$key]['is_checked'] = 1;
				}else{
					$role_info[$key]['is_checked'] = 0;
				}
			}
		}
		$this->assign('all_company', $all_company);
		$this->assign('company_info', $company_info);
		$this->assign("admin_id", $admin_id);
		$this->assign("role_data", $role_list);
                
		$this->assign("established_area_data", $established_area_list);
		$this->assign("admin_user_column_role_data", $admin_user_column_role_arr);
		$this->assign("admin_user_sys_menu_role_data", $admin_user_sys_menu_role_arr);
		$this->assign("area_role_id_data", $area_role_id_arr);
		$this->assign("area_role_name_data", $area_role_name_arr);
		$this->assign("role_info", $role_info);
		$this->display('editrole');
	}


	/**
	 * 进入重置密码页面
	 */
	function resetPwd()
	{
		$admin_id = I("param.admin_id", "");

		if (empty($admin_id)) {
			$this->error("参数错误！");
		}

		$this->assign('admin_id',$admin_id);
		$this->display('resetpwd');
	}


	/**
	 * 提交
	 */
	function adminUserPost()
	{
		$area_ids  =  rtrim(I("param.area_hidden_ids", ""),',');
		$real_name =  I("param.real_name", "");
		$username  =  I("param.username", "");
		$admin_pwd =  trim(I("param.admin_pwd", ""));
		$column_checbox   =  I("param.column_checbox", "");
		$sys_menu_checbox =  I("param.sys_menu_checbox", "");
		$role_list =  I("param.role_checbox", "");

		if (empty($real_name)) {
			$this->error("请填写姓名！");
		}
		if (empty($username)) {
			$this->error("请填写用户名！");
		}
		if (empty($admin_pwd)) {
			$this->error("请填写密码！");
		}
		if (strlen($admin_pwd) < 6 ||  strlen($admin_pwd) > 16) {
			$this->error("密码长度请保持在6-16位！");
		}
		//判断用户名是否 重复  有效账号 是单一的
		$is_user = $this->user_admin_model->where("username = '".$username."' and status = 1")->select();
		if($is_user){
			$this->error("创建失败，此用户名已存在");
		}


		//创建业务管理员
		$data['username'] = $username;
		$data['real_name'] = $real_name;
		$data['admin_pwd'] = sp_password($admin_pwd);//md5($admin_pwd);sp_password
		$data['type'] = '2';
		$data['status'] = '1';
		$data['company_id'] = I('company_id',0,'intval');
		$rid = $this->user_admin_model->add($data);

		if($rid){
			//添加业务管理员权限
			if($column_checbox){
				$column_data_list = array();
				foreach($column_checbox as $column_key=>$column_value){
					$column_data_list[] = array('column_id'=>$column_value,'admin_id'=>$rid);
				}
				$column_model = M('vrnews1.column_admin','news_');
				$column_model->addAll($column_data_list);
			}
			if($sys_menu_checbox){
				//默认的 业务管理、新闻业务、其它业务 三项  294、295、296
				//查看 业务及对应的子级 ID
				$sys_menu_str = implode(',',$sys_menu_checbox );
				$sys_menu_strs = $sys_menu_str.',294,295,296,305,317';
				$menu_model = M("vradmin1.sys_menu",null);
				$menu_get = $menu_model->where("parentid in (".$sys_menu_str.") and status = 1 or menu_id in(".$sys_menu_strs.")")->field("menu_id, name")->select();

				//处理员工管理权限
				if($menu_get){
					foreach($menu_get as $key=>$item){
						if($item['name'] == '公司管理'){
							unset($menu_get[$key]);
							if(!I('company_id',0,'intval')){
								$this->error("添加员工管理权限失败，请返回列表后重新编辑");
								exit();
							}
						}
					}
				}

				$menu_sons = array_column($menu_get,"menu_id" );


				$sys_menu_data_list = array();
				foreach($menu_sons as $sys_menu_key=>$sys_menu_value){
					$sys_menu_data_list[] = array('menu_id'=>$sys_menu_value,'admin_id'=>$rid, 'company_id'=>I('company_id',0,'intval'));
				}
				$column_model = M('vradmin1.menu_admin','sys_');
				$column_model->addAll($sys_menu_data_list);
			}else{
				$sys_menu_strs = '294,295,296,305,317';
				$menu_model = M("vradmin1.sys_menu",null);
				$menu_get = $menu_model->where(" status = 1 and menu_id in(".$sys_menu_strs.")")->field("menu_id")->select();
				$menu_sons = array_column($menu_get,"menu_id" );

				$sys_menu_data_list = array();
				foreach($menu_sons as $sys_menu_key=>$sys_menu_value){
					$sys_menu_data_list[] = array('menu_id'=>$sys_menu_value,'admin_id'=>$rid);
				}
				$column_model = M('vradmin1.menu_admin','sys_');
				$column_model->addAll($sys_menu_data_list);
			}

			//添加地区管理
			if($area_ids){
				$area_data_list = array();
				$area_arr = explode(',',$area_ids);
				foreach($area_arr as $area_key=>$area_value){
					$area_data_list[] = array('area_id'=>$area_value,'admin_id'=>$rid);
				}
				$area_model = M('vrnews1.admin','area_');
				$area_model->addAll($area_data_list);
			}

			//添加管理员角色
			if($role_list){
				for($i=0;$i<count($role_list);$i++){
					$admin_role = M("vradmin1.admin_role", null);
					$data = array();
					$data['admin_id']    = $rid;
					$data['role_id']     = $role_list[$i];
					$data['create_time'] = time();
					$admin_role->add($data);
				}
			}

			$successInfo = "添加成功";
			$this->success($successInfo, U("Admin/AdminUser/index"));
		}else{
			$this->error("创建失败！");
		}
	}


	/**
	 * 修改业务管理员权限提交
	 */
	function editRolePost()
	{
		$result = '0';
		$flag = true;
		$admin_id = I("param.admin_id", "");
		$area_ids = rtrim(I("param.area_hidden_ids", ""),',');
		$column_checbox =  I("param.column_checbox", "");
		$sys_menu_checbox =  I("param.sys_menu_checbox", "");
		$role_list =  I("param.role_list", "");

		if (empty($admin_id)) {
			echo $result;exit;
		}
		//管理员设置角色
		if($role_list){
			$admin_role = M("vradmin1.admin_role", null);
			$admin_role->where("admin_id = '".$admin_id."'")->delete();  //删除管理员原有的角色
			for($i=0;$i<count($role_list);$i++){
				$admin_role = M("vradmin1.admin_role", null);
				$data = array();
				$data['admin_id']    = $admin_id;
				$data['role_id']     = $role_list[$i];
				$data['create_time'] = time();
				$admin_role->add($data);
			}
		}else{
			$admin_role = M("vradmin1.admin_role", null);
			$admin_role->where("admin_id = '".$admin_id."'")->delete();  //删除管理员原有的角色
		}
		$data['company_id'] = I('company_id',0,'intval');
		$this->user_admin_model->where(['admin_id'=>$admin_id])->save($data);
		//编辑添加业务管理员权限
		if($column_checbox){
			$column_data_list = array();
			foreach($column_checbox as $column_key=>$column_value){
				$column_data_list[] = array('column_id'=>$column_value,'admin_id'=>$admin_id);
				$dataColumnids[] = $column_value;
			}
			$column_model = M('vrnews1.column_admin','news_');
			//清除
			$column_model->where('admin_id = '.$admin_id)->delete();
			//添加
			if($column_model->addAll($column_data_list)){
				//查看 对应的 直播权限管理员
				$live_admin = new ColumnLiveAdminModel();
				$live_admins = $live_admin->where("admin_id = ".$admin_id. " and type = 0")->select();
				//处理 对应的直播权限管理人
				foreach ($live_admins as $key=>$val){
					if(!in_array($val['column_id'], $dataColumnids)){
						$live_admin->where("id = ".$val['id'])->delete();
					}
				}
			}else{
				$flag = false;
			}
		}else{
			$column_model = M('vrnews1.column_admin','news_');
			//清除
			$column_model->where('admin_id = '.$admin_id)->delete();
			//清除 对应的 直播权限管理员
			$live_admin = new ColumnLiveAdminModel();
			$live_admin->where("admin_id = ".$admin_id. " and type = 0")->delete();
		}
		if($sys_menu_checbox){
			$sys_menu_data_list = array();

			//查看 业务及对应的子级 ID
			$sys_menu_str = implode(',', $sys_menu_checbox);
			$menu_model = M("vradmin1.sys_menu",null);
			$menu_get = $menu_model->where("parentid in (".$sys_menu_str.") and status = 1 or menu_id in(".$sys_menu_str.")")->field("menu_id, name")->select();

			if($menu_get){
				foreach($menu_get as $key=>$item){
					if($item['name'] == '公司管理'){
						unset($menu_get[$key]);
						if(!I('company_id',0,'intval')){
							echo 2;exit;
						}
					}
				}
			}

			$menu_sons = $this->_array_column($menu_get,"menu_id" );

			$menu_sons_str = implode(',', $menu_sons);
			foreach($menu_sons as $sys_menu_key=>$sys_menu_value){
				if($sys_menu_value == $this->manage_personnel_sys_menu_id){
					$sys_menu_data_list[] = array('menu_id'=>$sys_menu_value,'admin_id'=>$admin_id, 'company_id'=>I('company_id',0,'intval'));
				}else{
					$sys_menu_data_list[] = array('menu_id'=>$sys_menu_value,'admin_id'=>$admin_id, 'company_id'=>0);
				}
			}

//			foreach($sys_menu_checbox as $sys_menu_key=>$sys_menu_value){
//				$sys_menu_data_list[] = array('menu_id'=>$sys_menu_value,'admin_id'=>$admin_id);
//			}
			$column_model = M('vradmin1.menu_admin','sys_');
			//清除
			$column_model->where('admin_id = '.$admin_id." and menu_id  not in(294,295,296,305,317)")->delete();
			//添加
			if(!$column_model->addAll($sys_menu_data_list)) $flag = false;
		}else{
			$column_model = M('vradmin1.menu_admin','sys_');
			//清除
			$column_model->where('admin_id = '.$admin_id." and menu_id not in(294,295,296,305,317)")->delete();
		}
		//编辑地区
		if($area_ids){
			$area_arr = explode(',',$area_ids);
			$area_data_list = array();
			foreach($area_arr as $area_key=>$area_value){
				$area_data_list[] = array('area_id'=>$area_value,'admin_id'=>$admin_id);
				$dataColumnids[] = $area_value;
			}
			$area_model = M('vrnews1.admin','area_');
			//清除
			$area_model->where('admin_id = '.$admin_id)->delete();
			//添加
			if($area_model->addAll($area_data_list)){
				//查看 对应的 直播权限管理员
				$live_admin = new ColumnLiveAdminModel();
				$live_admins = $live_admin->where("admin_id = ".$admin_id. " and type = 1")->select();
				//处理 对应的直播权限管理人
				foreach ($live_admins as $key=>$val){
					if(!in_array($val['column_id'], $dataColumnids)){
						$live_admin->where("id = ".$val['id'])->delete();
					}
				}
			}else{
				$flag = false;
			}
		}else{
			$area_model = M('vrnews1.admin','area_');
			//清除
			$area_model->where('admin_id = '.$admin_id)->delete();

			//清除 对应的 直播权限管理员
			$live_admin = new ColumnLiveAdminModel();
			$live_admin->where("admin_id = ".$admin_id. " and type = 1")->delete();
		}
		$this->getAdminRole($admin_id);
		if($flag) $result =1;
		echo $result;
	}


	/**
	 * 重置密码提交
	 */
	function resetPwdPost()
	{
		$result = '0';
		$admin_id = I("param.admin_id", "");
		$old_pwd = I("param.old_pwd", "");
		$new_pwd = I("param.new_pwd", "");
		$new_pwd_again = I("param.new_pwd_again", "");

		if (empty($admin_id)) {
			$this->error("参数错误！");
		}

		$admin_info = $this->user_admin_model->where('admin_id = '.$admin_id)->field('admin_pwd')->find();

		if($this->self_admin_model['type'] == '1'){
			//当前为超管 此功能目前不存在，以下代码 目前无效
			if(!sp_compare_password('123456',$admin_info['admin_pwd'])){
				$data['admin_pwd'] = sp_password('123456');
				if(!$this->user_admin_model->where('admin_id = '.$admin_id)->data($data)->save()){
					$this->error($result['Message']);
				}
			}
			$this->success("修改成功");
		}else{
			if (empty($old_pwd)) {
				$this->error("请填写旧密码！");
			}

			if (empty($new_pwd)) {
				$this->error("请填写新密码！");
			}

			if (empty($new_pwd_again)) {
				$this->error("请确认新密码！");
			}

			if($new_pwd !=$new_pwd_again){
				$this->error("两次新密码输入不一致！");
			}

			if(sp_compare_password($old_pwd,$admin_info['admin_pwd'])){
				if($admin_info['admin_pwd'] != $new_pwd){
					$data['admin_pwd'] = sp_password($new_pwd);
					if($this->user_admin_model->where('admin_id = '.$admin_id)->data($data)->save()){
						$result = '1';
					}else{
						$this->error("操作失败！");
					}
				}else{
					$result = '1';
				}
			}else{
				$this->error("密码错误！");
			}
			echo $result;
		}






	}


	/**
	 * 业务管理员删除
	 */
	function del()
	{
		$adminUserId = I('param.adminUserId', "");
		if (empty($adminUserId)) {
			$this->error("参数错误！");
		}
		$result = $this->user_admin_model->adminUserDel($adminUserId);
		if ($result) {
			$this->success("删除成功！");
		} else {
			return $this->error($result['Message']);
		}
	}
         protected function _array_column($input, $columnKey, $indexKey = NULL) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array) $input AS $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }

            $result[$key] = $tmp;
        }

        return $result;
    }

}

